package com.hadwinling.blog.mvc;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author HadwinLing
 * @version V1.0
 * @Package com.hadwinling.myblog.mvc
 * @date 2020/7/3 10:29
 */
@Component
public class AdminUriInterceptor implements HandlerInterceptor {

    /**
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     * 在请求处理之前进行拦截
     * 如果是已登录 放行 返回true
     * 如果是没登陆状态 不放行 返回false 去登录
     * 自定义对哪些请求进行拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取登录的Uri
        String requestURI = request.getRequestURI();
        //登录请求放心
        //根据项目定义需要拦截的请求
        //如果是登录请求或者不需要登录的请求进行放行
        if (requestURI.endsWith("/admin/login")){
            return true;
        }
        //判断管理员是否已经登录
        HttpSession session = request.getSession();
        Object currAdmin = session.getAttribute("currAdmin");
        if (currAdmin!=null){
            //已登录
            return true;
        }

        //未登录 要求用户去登录
        request.getRequestDispatcher("/admin/login").forward(request,response);
        return false;
    }
}
